﻿using AnesSystem.Models;
using AnesSystem.Services;
using AnesSystem.ViewModels;
using Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using System.Xml.Linq;

namespace AnesSystem.Controls
{
    /// <summary>
    /// 基础自定义类 只作用于PatienLinkModel对象
    /// </summary>
    public class BaseCustomCtrl : UserControl, INotifyPropertyChanged
    {
        #region Variables

        private UIElement _control;

        private object preValue;

        #endregion

        #region Constructor

        public BaseCustomCtrl()
        {
            _control = new UIElement();
            this.GotFocus += BaseCustomCtrl_GotFocus;
            this.Loaded += BaseCustomCtrl_Loaded;
            SaveModel = 1;
        }
        #endregion

        #region Properties

        public double BHeight
        {
            set
            {
                this.Height = value;
            }
        }

        public double BWidth
        {
            set
            {
                this.Width = value;
            }
        }

        /// <summary>
        /// 保存模式 1：不通过当前控件更新数据库,只是作为界面绑定用
        ///          2：通过当前控件更新数据库（必须指定FieldName、ClassName和是必须当前页面独有的字段）
        ///          3：通过当前控件更新数据库不需要指定FieName、ClassName，例如麻醉单或者有数据关联的字段
        /// </summary>
        public int SaveModel { get; set; }

        /// <summary>
        /// 获取或设置对应的字段名称
        /// </summary>
        public string FieldName { get; set; }

        /// <summary>
        /// 获取或设置对应的类名称
        /// </summary>
        public string ClassName { get; set; }

        /// <summary>
        /// 手术对象,仅在非绑定表单时使用,需要配合field和className使用
        /// </summary>
        public PatientLinkModel PatientLink
        {
            get { return (PatientLinkModel)GetValue(PatientLinkProperty); }
            set { SetValue(PatientLinkProperty, value); }
        }

        // Using a DependencyProperty as the backing store for PatientLink.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PatientLinkProperty =
            DependencyProperty.Register("PatientLink", typeof(PatientLinkModel), typeof(BaseCustomCtrl), new PropertyMetadata(null));


        #region 依赖属性



        public TextAlignment TextAlignment
        {
            get { return (TextAlignment)GetValue(TextAlignmentProperty); }
            set { SetValue(TextAlignmentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for TextAlignment.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextAlignmentProperty =
            DependencyProperty.Register("TextAlignment", typeof(TextAlignment), typeof(BaseCustomCtrl), new PropertyMetadata(TextAlignment.Center));



        public object DefaultValue
        {
            set
            {
                Value = value;
            }
        }

        /// <summary>
        /// 值属性
        /// </summary>
        public object Value
        {
            get { return (object)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(BaseCustomCtrl), new PropertyMetadata("", new PropertyChangedCallback(ValueChangedCallBack)));

        public static void ValueChangedCallBack(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            try
            {
                BaseCustomCtrl ctrl = obj as BaseCustomCtrl;
                if (args.NewValue == null) return;
                if (args.NewValue.Equals(ctrl.preValue)) return;
                ctrl.preValue = args.NewValue;
                ctrl.ValueChanged?.Invoke(ctrl, null);
                if (DataManager.Instance.IsNotNeedSaveData)
                {

                }
                else
                {
                    switch (ctrl.SaveModel)
                    {
                        case 1:

                            break;
                        case 2:
                            if (DataManager.Instance.CurrentPatientLink != null && !string.IsNullOrEmpty(ctrl.ClassName) && DataManager.Instance.CurrentPatientLink.Tables.ContainsKey(ctrl.ClassName))
                            {
                                DataManager.Instance.FillAndSaveXMLTableAndCtrlValue(ctrl.FieldName, ctrl.Value.ToString(), ctrl);
                            }
                            break;
                        case 3:
                            if (DataManager.Instance.CurrentPatientLink != null)
                            {
                                PatientLinkService.Instance.Update(DataManager.Instance.CurrentPatientLink);
                            }
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error("BaseCustomCtrl", ex);
            }
        }
        #endregion


        #endregion

        #region Event

        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler ValueChanged;

        #endregion

        #region Private Methods

        #endregion

        #region Public/Protected Methods



        #endregion

        #region EventHandlers

        public void RaisePropertyChanged(string propertyName)
        {
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChanged?.Invoke(Value, e);
        }

        private void BaseCustomCtrl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {

        }

        private void BaseCustomCtrl_GotFocus(object sender, RoutedEventArgs e)
        {
            if (DataManager.Instance.CurrentPatientLink != null)
            {
                Mapper(PatientLinkService.Instance.GetObjById(DataManager.Instance.CurrentPatientLink.Id.ToString()), DataManager.Instance.CurrentPatientLink);
            }
        }
        /// <summary>
        /// 传入类型A的对象a,类型B的对象b，将b和a相同名称的值进行赋值给a
        /// </summary>
        /// <typeparam name="A"></typeparam>
        /// <typeparam name="B"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        public void Mapper<PatientLinkModel>(PatientLinkModel newObj, PatientLinkModel oldObj)
        {
            try
            {
                Type Typeb = newObj.GetType();//获得类型  
                Type Typea = typeof(PatientLinkModel);
                foreach (PropertyInfo sp in Typeb.GetProperties())//获得类型的属性字段  
                {
                    if (sp.CanWrite)
                    {
                        sp.SetValue(oldObj, sp.GetValue(newObj, null), null);//获得b对象属性的值复制给a对象的属性  
                    }
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }

        #endregion

    }
}
